package com.ellecity06.common.ktx

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest

/**
 * @author ellecity06
 * @time 2023/4/13 10:31
 * @des
 */
fun <T> SharedFlow<List<T>>.observeEvent(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) {
    lifecycleOwner.lifecycleScope.launchWhenCreated {
        this@observeEvent.collect {
            it.forEach { event ->
                action.invoke(event)
            }
        }
    }
}
//fun <T> Flow<T>.observeEvent2(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) {
//    lifecycleOwner.lifecycleScope.launchWhenStarted {
//        this@observeEvent2.collect(action)
//    }
//}
fun <T> StateFlow<T?>.observeEvent(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) {
    lifecycleOwner.lifecycleScope.launchWhenCreated {

        this@observeEvent.collectLatest {
            if (it == null) return@collectLatest
            action.invoke(it)

        }
    }
}

fun <T> sharedFlowEvents() = SharedFlowEvents<T>()
suspend fun <T> SharedFlowEvents<T>.postEvent(vararg values: T) {
    this.emit(values.toList())
}
suspend fun <T> MutableStateFlow<T>.postEvent( values: T) {
    this.emit(values)
}
typealias SharedFlowEvents<T> = MutableSharedFlow<List<T>>

@Suppress("FunctionName")
fun <T> SharedFlowEvents(): SharedFlowEvents<T> {
    return MutableSharedFlow(replay = 0, extraBufferCapacity = 0)
}
//@Suppress("FunctionName")
//fun <T> stateFlowEvents(data:T): SharedFlowEvents<T> {
//    return MutableStateFlow(data)
//}